package com.sky.service.admin.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品及口味
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //想菜品表插入1条数据
        dishMapper.insert(dish);

        //获取insert语句生成的主键
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!CollectionUtils.isEmpty(flavors)) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);

            clealCache();
        }
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO,dish);

        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<Dish> page =(Page<Dish>)dishMapper.list(dish);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 菜品批量删除
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        log.info("菜品批量删除：{}", ids);
        //查询菜品是否在售
        Integer count = dishMapper.selectCountByIdsAndStatus(ids, StatusConstant.ENABLE);
        if (count > 0) {
            throw new BaseException("菜品在售，不能删除");
        }
        //查询删除的菜品是否有被套餐关联的
        Integer count2 = setmealDishMapper.selectCountByDishIds(ids);
        if (count2 > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //都没有，删除菜品的口味信息
        dishFlavorMapper.deleteByDishIds(ids);

        //删除菜品信息
        dishMapper.deleteByIds(ids);

        clealCache();
    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        DishVO dishVO = dishMapper.getDishById(id);
        dishVO.setFlavors(dishFlavorMapper.getFlavorByDishId(id));
        return dishVO;
    }

    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        dishMapper.update(dish);

        //修改dish_flavor
        //先删除原有数据
        dishFlavorMapper.deleteByDishId(dish.getId());
        //添加新的数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
        });
        dishFlavorMapper.batchSave(flavors);
        clealCache();
    }

    @Override
    public List<Dish> getDishByCategoryId(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)//启用
                .build();
        List<Dish> dishList = dishMapper.list(dish);
        return dishList;
    }

    private void clealCache(){
        Set keys = redisTemplate.keys(RedisConstant.CATEGORY_CACHE_PREFIX + "*");
        redisTemplate.delete(keys);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        String key = RedisConstant.CATEGORY_CACHE_PREFIX + dish.getCategoryId();
        String jsonSring =(String) redisTemplate.opsForValue().get(key);
        if (StringUtils.hasText(jsonSring)){
            log.info("从缓存中查询,categoryId:{}",dish.getCategoryId());
            return JSONObject.parseArray(jsonSring,DishVO.class);
        }

        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getFlavorByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        redisTemplate.opsForValue().set(key, JSON.toJSONString(dishVOList));

        return dishVOList;
    }

}
